﻿using System;
using System.Linq;
using System.Text;
using System.Web;
using EntityFramework.Extensions;
using System.IO;
using System.Web.Mvc;
using Newtonsoft.Json;
using LJSheng.Data;
using static LJSheng.Web.LJShengHelper;
using LJSheng.Common;
using System.Drawing;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace LJSheng.Web
{
    /// <summary>
    /// 帮助类
    /// </summary>
    public static class Helper
    {
        #region 订单操作
        /// <summary>
        /// 订单操作
        /// </summary>
        /// <param name="order_no">网站订单号</param>
        /// <param name="trade_no">网银订单号</param>
        /// <param name="pay_type">支付类型</param>
        /// <param name="pay_amount">在线支付金额</param>
        /// <param name="beizhu">返回的支付备注信息</param>
        /// <returns>返回调用结果</returns>
        public static bool Order(string order_no, string trade_no, int pay_type, decimal pay_amount, string beizhu)
        {
            JObject paramJson = null;
            try
            {
                paramJson = JsonConvert.DeserializeObject(beizhu) as JObject;
            }
            catch
            {
                LogManager.WriteLog("解析参数错误", beizhu);
            }
            int lx = Int32.Parse(paramJson["lx"].ToString());
            bool isok = false;
            string LogMsg = "订单号:" + order_no + ",网银订单号:" + trade_no + ",支付类型:" + pay_type.ToString() + ",网上支付金额:" + pay_amount.ToString() + ",备注:" + beizhu;
            //支付类型
            string payname = ((PayType)Enum.Parse(typeof(LJShengHelper.PayType), pay_type.ToString())).ToString();
            using (EFDB db = new EFDB())
            {
                var b = db.LOrder.Where(l => l.order_no == order_no).FirstOrDefault();
                if (b!=null && b.pay_status != 1)
                {
                    if (b.rmb == pay_amount)
                    {
                        b.pay_status = 1;
                    }
                    else
                    {
                        b.pay_status = 5;
                    }
                    b.trade_no = trade_no;
                    b.pay_time = DateTime.Now;
                    b.pay_type = pay_type;
                    b.pay_amount = pay_amount;
                    b.remarks = beizhu;
                    //返利
                    if (db.SaveChanges() == 1)
                    {
                        isok = true;
                        LogManager.WriteLog(payname + "更新订单成功", LogMsg);
                        if (b.pay_status == 1)
                        {
                            fl(b.buygid,b.usergid, b.gid, b.tgf, pay_amount, b.user_cash, lx, payname, LogMsg);
                        }
                        else
                        {
                            LogManager.WriteLog(payname + "支付金额异常", LogMsg);
                        }
                    }
                    else
                    {
                        LogManager.WriteLog(payname + "更新订单失败", LogMsg);
                    }
                }
            }
            return isok;
        }
        /// <summary>
        /// 返利逻辑
        /// </summary>
        /// <param name="buygid">商家gid</param>
        /// <param name="usergid">购买用户的gid</param>
        /// <param name="ddgid">订单gid</param>
        /// <param name="tgf">推广费</param>
        /// <param name="pay_amount">网上支付金额</param>
        /// <param name="user_cash">提现金额</param>
        /// <param name="lx">0=会员消费 1=会员注册 2=商家注册</param>
        /// <param name="payname">支付名称</param>
        /// <param name="LogMsg">日志</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static void fl(Guid buygid, Guid usergid,Guid ddgid,decimal tgf,decimal pay_amount,decimal user_cash,int lx,string payname,string LogMsg)
        {
            using (EFDB db = new EFDB())
            {
                var s = db.ShopList.Where(l => l.gid == buygid).FirstOrDefault();
                var u = db.LUser.Where(l => l.gid == usergid).FirstOrDefault();
                //购买会员套餐
                if (lx == 1)
                {
                    u.grade = s.tese;
                    if (db.SaveChanges() == 1)
                    {
                        UPCKUser(usergid);
                    }
                    else
                    {
                        LogManager.WriteLog(payname + "支付成功更新会员失败", LogMsg);
                    }
                }
                //购买商家套餐
                if (lx == 2)
                {
                    var sg = db.ShopList.Where(l => l.usergid == usergid).FirstOrDefault();
                    sg.grade = s.tese;
                    if (db.SaveChanges() == 1)
                    {
                        UPCKShop(usergid);
                    }
                    else
                    {
                        LogManager.WriteLog(payname + "支付成功更新商家失败", LogMsg);
                    }
                }
                //商家订单处理
                if (lx == 0)
                {
                    //商家提现
                    PayFL(s.usergid, ddgid, user_cash, 3, u.account);
                    //消费返利
                    Guid? ugid = GetUser(usergid, ddgid, tgf * 0.5M, lx);
                    if (ugid != null)
                    {
                        ugid = GetUser((Guid)ugid, ddgid, tgf * 0.3M, lx);
                        if (ugid != null)
                        {
                            ugid = GetUser((Guid)ugid, ddgid, tgf * 0.2M, lx);
                        }
                    }
                }
                else
                {
                    GetUser(usergid, ddgid, pay_amount * 0.2M, lx);
                }
            }
        }
        /// <summary>
        /// 注册上级提成
        /// </summary>
        /// <param name="gid">购买用户的gid</param>
        /// <param name="ddgid">订单gid</param>
        /// <param name="tgf">推广费</param>
        /// <param name="lx">0=会员消费 1=会员注册 2=商家注册</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static Guid? GetUser(Guid gid, Guid ddgid, decimal tgf, int lx)
        {
            using (EFDB db = new EFDB())
            {
                var b = db.LUser.Where(l => l.gid == gid).GroupJoin(db.LUser,
                    x => x.usergid,
                    y => y.gid,
                    (x, y) => new
                    {
                        x.account,//支付用户帐号
                        usergid =y.FirstOrDefault().gid,//购买用户的上级
                        y.FirstOrDefault().lx,
                        y.FirstOrDefault().grade,
                        ugid = y.FirstOrDefault().usergid//购买用户的上级的上级
                    }).FirstOrDefault();
                if (b != null && b.usergid != null)
                {
                    //注册返利
                    if (b.grade == "中级会员" || b.grade == "高级会员" || b.lx == 3)
                    {
                        PayFL(b.usergid, ddgid, tgf, lx, b.account);
                    }
                    if (b.ugid != null)
                    {
                        return b.usergid;
                    }
                }
                return null;
            }
        }
        /// <summary>
        /// 会员消费商家提现
        /// </summary>
        /// <param name="usergid">商家/会员gid</param>
        /// <param name="ddgid">订单gid</param>
        /// <param name="tgf">推广费</param>
        /// <param name="lx">0=会员消费 1=会员注册 2=商家注册 3=商家提现</param>
        /// <param name="account">消费会员</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static Guid? PayFL(Guid usergid, Guid ddgid, decimal tgf, int lx,string account)
        {
            using (EFDB db = new EFDB())
            {
                if (db.Pay.Where(l => l.ddgid == ddgid && l.usergid == usergid && l.lx==lx).FirstOrDefault() == null)
                {
                    var p = new Pay();
                    p.gid = Guid.NewGuid();
                    p.addtime = DateTime.Now;
                    p.usergid = usergid;
                    p.ddgid = ddgid;
                    p.pay_status = 2;
                    p.pay_type = 2;
                    p.rmb = tgf;
                    p.lx = lx;
                    p.remarks = "";
                    db.Pay.Add(p);
                    if (db.SaveChanges() != 1)
                    {
                        LogManager.WriteLog("返利失败", "会员=" + usergid.ToString() + ",订单=" + ddgid.ToString() + ",返利金额=" + tgf.ToString() + ",类型=" + lx);
                    }
                }
                else
                {
                    LogManager.WriteLog("重复返利", "会员=" + usergid.ToString() + ",订单=" + ddgid.ToString() + ",返利金额=" + tgf.ToString() + ",类型=" + lx);
                }
                return null;
            }
        }
        /// <summary>
        /// 微信下单
        /// </summary>
        /// <param name="buygid">商品gid</param>
        /// <param name="body">商品名称</param>
        /// <param name="lx">0=消费 1=会员注册 2=商家注册</param>
        /// <param name="amount">总金额</param>
        /// <param name="rmb">实际支付</param>
        /// <param name="user_cash">平台收取佣金金额</param>
        /// <param name="price">单品价格</param>
        /// <param name="num">数量</param>
        /// <param name="ptf">平台收取30%</param>
        /// <param name="hyfwf">会员服务费40%</param>
        /// <param name="tgf">专属推广费30%[一级=15% 二级=9% 三级=6%]</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static string wxpay(Guid buygid,string body, int lx,decimal amount, decimal rmb,decimal user_cash, decimal price, int num, decimal ptf, decimal hyfwf, decimal tgf)
        {
            string rzt = "{\"appId\":\"payerr\",\"return_msg\":\"初始化失败\"}";
            Guid gid = lx == 2 ? LCookie.GetShop(1) : LCookie.GetUser();
            if (gid != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                using (EFDB db = new EFDB())
                {
                    decimal irmb = Math.Round(rmb, MidpointRounding.AwayFromZero);
                    decimal iuser_cash = Math.Round(user_cash, MidpointRounding.AwayFromZero);
                    string order_no = RandStr.CreateOrderNO();
                    //生成订单
                    var b = new LOrder();
                    b.gid = Guid.NewGuid();
                    b.addtime = DateTime.Now;
                    b.usergid = gid;
                    b.buygid = buygid;
                    b.order_no = order_no;
                    b.pay_status = 2;
                    b.pay_type = 2;
                    b.amount = amount;
                    b.rmb = irmb;
                    b.pay_amount = 0;
                    b.user_cash = irmb - iuser_cash;
                    b.price = price;
                    b.num = num;
                    b.coupon_price = 0;
                    b.coupon_number = "";
                    b.ptf = iuser_cash * ptf;
                    b.hyfwf = iuser_cash * hyfwf;
                    b.tgf = iuser_cash * tgf;
                    db.LOrder.Add(b);
                    if (db.SaveChanges() == 1)
                    {
                        string beizhu = JsonConvert.SerializeObject(new {  lx, irmb, buygid, gid });//备注
                        //开始微信统一下单
                        string _Pay_Package = "";
                        //微信jspai支付
                        if (_Pay_Package.Length > 0)
                        {
                            rzt = _Pay_Package;
                        }
                        else
                        {
                            db.LOrder.Where(l => l.gid == b.gid).Delete();
                        }
                    }
                    else
                    {
                        rzt = "{\"appId\":\"payerr\",\"return_msg\":\"提交订单失败\"}";
                    }
                }
            }
            else
            {
                rzt = "{\"appId\":\"payerr\",\"return_msg\":\"登录异常\"}";
            }
            return rzt;
        }
        #endregion

        #region 文件上传
        /// <summary> 
        /// 多文件上传的操作
        /// </summary> 
        /// <param name="path">上传路径</param>
        /// <param name="files">文件集合</param> 
        public static string UploadFiles(string path, HttpFileCollection files)
        {
            StringBuilder sb = new StringBuilder();
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))  //判断当前目录是否存在。
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));  //建立上传文件存放目录。
            }
            foreach (string f in files.AllKeys)
            {
                HttpPostedFile file = files[f];
                string fl = Common.RandStr.CreateOrderNO() + file.FileName;
                file.SaveAs(HttpContext.Current.Server.MapPath(path + fl));
                sb.Append(fl + "$");
            }
            return sb.ToString().TrimEnd('$');
        }

        /// <summary>
        /// 压缩上传
        /// </summary>
        /// <param name="base64str"></param>
        /// <returns></returns>
        public static string jsimg(string path,string base64str)
        {
            string FileName = "";
            try
            {
                if (!string.IsNullOrEmpty(base64str))
                {
                    string imgData = base64str.Split(',')[1];
                    //过滤特殊字符即可   
                    string dummyData = imgData.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
                    if (dummyData.Length % 4 > 0)
                    {
                        dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
                    }
                    byte[] byteArray = Convert.FromBase64String(dummyData);
                    using (MemoryStream ms = new MemoryStream(byteArray))
                    {
                        Image img = Image.FromStream(ms);
                        path = HttpContext.Current.Server.MapPath(path);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        FileName = Guid.NewGuid() + ".jpg";
                        img.Save(path + FileName);
                    }
                }
            }
            catch { }
            return FileName;
        }

        #endregion

        #region POST文件上传
        /// <summary> 
        /// POST有多文件上传的操作
        /// </summary> 
        /// <param name="path">上传路径</param>
        /// <param name="file">文件</param> 
        public static string UploadFiles(string path, HttpPostedFileBase file)
        {
            StringBuilder sb = new StringBuilder();
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))  //判断当前目录是否存在。
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));  //建立上传文件存放目录。
            }
            string filename = Common.RandStr.CreateOrderNO() + Path.GetExtension(file.FileName);
            file.SaveAs(HttpContext.Current.Server.MapPath(path + filename));
            return filename;
        }
        #endregion

        #region 请求时候的IP
        /// <summary>
        /// 请求时候的IP
        /// </summary>
        public static string IP
        {
            get
            {
                string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (String.IsNullOrEmpty(ip))
                {
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                return ip;
            }
        }
        #endregion

        #region 操作提示
        public static RedirectResult WebRedirect(string title, string url, string msg, string href="")
        {
            return new RedirectResult("/ljsheng/msg?msg=" + msg + "&href="+ HttpContext.Current.Server.UrlEncode(href) + "&url=" + HttpContext.Current.Server.UrlEncode(url) + "&title=" + title);
        }
        public static RedirectResult Redirect(string title, string url, string msg)
        {
            return new RedirectResult("/home/msg?msg=" + msg + "&url=" + HttpContext.Current.Server.UrlEncode(url) + "&title=" + title);
        }
        public static RedirectResult Redirect(string msg)
        {
            return new RedirectResult("/home/msg?msg=" + msg);
        }
        #endregion

        #region 更新登录信息
        /// <summary>
        /// 用户登录信息CK
        /// </summary>
        /// <param name="gid">用户gid</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static void UPCKUser(Guid gid)
        {
            using (EFDB db = new EFDB())
            {
                LCookie.DelCookie("linjiansheng");
                //会员登录信息
                var u = db.LUser.Where(l => l.gid == gid).FirstOrDefault();
                if (u != null)
                {
                    LCookie.AddCookie("linjiansheng", DESRSA.DESEnljsheng(JsonConvert.SerializeObject(new
                    {
                        u.gid,
                        u.account,
                        u.loginid
                    })), 30);
                }
            }
        }

        /// <summary>
        /// 商家登录信息CK
        /// </summary>
        /// <param name="gid">用户gid</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static void UPCKShop(Guid gid)
        {
            using (EFDB db = new EFDB())
            {
                LCookie.DelCookie("shop");
                LCookie.DelCookie("linjiansheng");
                //如果是商家
                var s = db.LUser.Where(l => l.gid == gid).FirstOrDefault();
                if (s != null)
                {
                    LCookie.AddCookie("shop", DESRSA.DESEnljsheng(JsonConvert.SerializeObject(new
                    {
                        s.gid,
                        s.account,
                        s.loginid
                    })), 30);
                    UPCKUser(s.gid);
                }
                //设置用户读取数据的城市
                if (string.IsNullOrEmpty(LCookie.GetCookie("city")))
                {
                    LCookie.AddCookie("city", s.city, 30);
                }
            }
        }
        #endregion

        #region 推荐人操作
        /// <summary>
        /// 推荐人判断
        /// </summary>
        /// <param name="account">推荐人帐号</param>
        /// <param name="lx">注册类型[1=会员 2=商家]</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static string tjr(string account, string lx)
        {
            using (EFDB db = new EFDB())
            {
                var b = db.LUser.Where(l => l.account == account).FirstOrDefault();
                if (b != null)
                {
                    if (lx == "0")
                    {
                        return JsonConvert.SerializeObject(new AjaxResult(b.gid));
                    }
                    else if (lx == "2")
                    {
                        if (b.grade == "高级会员")
                        {
                            return JsonConvert.SerializeObject(new AjaxResult(b.gid));
                        }
                        else
                        {
                            return JsonConvert.SerializeObject(new AjaxResult(300, "商家的推荐人须是高级会员"));
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(b.grade))
                        {
                            if (b.lx == 3)
                            {
                                if (string.IsNullOrEmpty(db.ShopList.Where(s => s.usergid == b.gid).FirstOrDefault().grade))
                                {
                                    return JsonConvert.SerializeObject(new AjaxResult(300, "该商家未正式入驻!"));
                                }
                                else
                                {
                                    return JsonConvert.SerializeObject(new AjaxResult(b.gid));
                                }
                            }
                            else
                            {
                                return JsonConvert.SerializeObject(new AjaxResult(300, "推荐人必须是会员"));
                            }
                        }
                        else
                        {
                            return JsonConvert.SerializeObject(new AjaxResult(b.gid));
                        }
                    }
                }
                else
                {
                    return JsonConvert.SerializeObject(new AjaxResult(300, account + " 帐号不存在"));
                }
            }
        }

        /// <summary>
        /// 推荐人列表
        /// </summary>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static string userlist(string gid)
        {
            using (EFDB db = new EFDB())
            {
                Guid usergid = Guid.Parse(gid);
                var b = db.LUser.Where(l => l.usergid == usergid).Select(l => new {
                    l.account,
                    l.addtime,
                    l.gid,
                    grade = l.lx == 3 ? db.ShopList.Where(s => s.usergid == l.gid).FirstOrDefault().grade : l.grade
                }).AsQueryable();
                //开始分页
                int pageindex = 1;
                int pagesize = 888;//每页显示的数量
                return JsonConvert.SerializeObject(new AjaxResult(new { list = b.OrderByDescending(l => l.addtime).Skip(pagesize * (pageindex - 1)).Take(pagesize).ToList() }));
            }
        }
        #endregion

        #region 商家操作
        /// <summary>
        /// 商家收入
        /// </summary>
        /// <param name="gid">商家的usergid</param>
        /// <param name="pstime">收入开始时间</param>
        /// <param name="petime">收入结束时间</param>
        /// <returns>返回调用结果</returns>
        /// <para name="result">200 是成功其他失败</para>
        /// <para name="data">对象结果</para>
        /// <remarks>
        /// 2018-08-18 林建生
        /// </remarks>
        public static string GetShopRMB(Guid gid,string stime, string etime)
        {
            using (EFDB db = new EFDB())
            {
                var b = db.Pay.Where(l => l.usergid == gid && l.lx == 3).AsQueryable();
                //时间查询
                if (!string.IsNullOrEmpty(stime) || !string.IsNullOrEmpty(etime))
                {
                    DateTime? st = null;
                    DateTime? et = null;
                    if (!string.IsNullOrEmpty(stime) && string.IsNullOrEmpty(etime))
                    {
                        st = DateTime.Parse(DateTime.Parse(stime).ToString("yyyy-MM-dd") + " 00:00:00");
                        et = DateTime.Parse(DateTime.Parse(stime).ToString("yyyy-MM-dd") + " 23:59:59");
                    }
                    else if (string.IsNullOrEmpty(stime) && !string.IsNullOrEmpty(etime))
                    {
                        st = DateTime.Parse(DateTime.Parse(etime).ToString("yyyy-MM-dd") + " 00:00:00");
                        et = DateTime.Parse(DateTime.Parse(etime).ToString("yyyy-MM-dd") + " 23:59:59");
                    }
                    else
                    {
                        st = DateTime.Parse(stime);
                        et = DateTime.Parse(etime);
                    }
                    b = b.Where(l => l.addtime >= st && l.addtime <= et);
                }
                if (b.Count() >0)
                {
                    return b.Sum(l => l.rmb).ToString();
                }
                return "0";
            }
        }
        #endregion

        #region 三级关系人数
        public static int fs(List<User> User,Guid gid,int loop)
        {
            loop--;
            int num = 0;
            var fs = User.Where(l => l.usergid == gid).ToList();
            num = fs.Count();
            if (loop != 0)
            {
                foreach (var dr in fs)
                {
                    num += Helper.fs(User, dr.gid, loop);
                }
            }
            return num;
        }

        /// <summary>
        /// 增加推荐人人数
        /// </summary>
        /// <param name="gid">用户Gid</param>
        /// <param name="number">第几级</param>
        /// <param name="loop">找几级</param>
        /// <returns>请求结果</returns>
        public static void M(Guid? gid, int number, int loop)
        {
            if (number <= loop)
            {
                using (EFDB db = new EFDB())
                {
                    var b = db.LUser.Where(l => l.gid == gid).FirstOrDefault();
                    if (b != null)
                    {
                        number++;
                        b.number = b.number + 1;
                        db.SaveChanges();
                        if (b.usergid != null)
                        {
                            M(b.usergid, number, loop);
                        }
                    }
                }
            }
        }
        #endregion
    }
    public class User
    {
        public Guid gid { get; set; }
        public Guid? usergid { get; set; }
    }
}